#include "msgCore.h"

#include "nsExchangeMailFolder.h"
#include "nsIEnumerator.h"
#include "nsILocalFile.h"
#include "nsCOMPtr.h"

#include "nsMsgDBCID.h"
#include "nsIMsgDatabase.h"
#include "nsIMsgFolderNotificationService.h"

NS_IMPL_ISUPPORTS_INHERITED0(nsExchangeMailFolder,
                             nsMsgDBFolder)

nsExchangeMailFolder::nsExchangeMailFolder() {}
nsExchangeMailFolder::~nsExchangeMailFolder() {}

//Makes sure the database is open and exists.  If the database is valid then
//returns NS_OK. Otherwise returns a failure error value.
nsresult
nsExchangeMailFolder::GetDatabase()
{
  nsresult rv = NS_OK;
  if (!mDatabase)
  {
    nsCOMPtr<nsIMsgDBService> msgDBService = do_GetService(NS_MSGDB_SERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Create the database, blowing it away if it needs to be rebuilt
                                    /* aLeaveInvalidDB */
    rv = msgDBService->OpenFolderDB(this, PR_FALSE, getter_AddRefs(mDatabase));
    if (NS_FAILED(rv))
      rv = msgDBService->CreateNewDB(this, getter_AddRefs(mDatabase));
    NS_ENSURE_SUCCESS(rv, rv);

    if(mDatabase)
    {
      UpdateNewMessages();
      if(mAddListener)
        mDatabase->AddListener(this);
      // UpdateSummaryTotals can null mDatabase during initialization, so we save a local copy
      nsCOMPtr<nsIMsgDatabase> database(mDatabase);
      UpdateSummaryTotals(PR_TRUE);
      mDatabase = database;
    }
  }
  return rv;
}

NS_IMETHODIMP
nsExchangeMailFolder::UpdateFolder(nsIMsgWindow *msgWindow)
{
  nsresult rv;
  
  rv = GetDatabase();
  if (NS_FAILED(rv))
  {
    ThrowAlertMsg("errorGettingDB", msgWindow);
    return rv;
  }

  NotifyFolderEvent(mFolderLoadedAtom); 
  return rv;
}

nsresult nsExchangeMailFolder::CreateChildFromURI(const nsCString &uri, nsIMsgFolder **folder)
{
  nsExchangeMailFolder *newFolder = new nsExchangeMailFolder;
  if (!newFolder)
    return NS_ERROR_OUT_OF_MEMORY;
  newFolder->Init(uri.get());
  NS_ADDREF(*folder = newFolder);
  return NS_OK;
}

NS_IMETHODIMP nsExchangeMailFolder::GetMessages(nsISimpleEnumerator **result)
{
  NS_ENSURE_ARG_POINTER(result);
  if (!mDatabase)
    GetDatabase();
  if (mDatabase)
    return mDatabase->EnumerateMessages(result);
  return NS_ERROR_UNEXPECTED;
}

static const char kExchangeRootURI[] = "exchange:/";
static const char kExchangeMessageRootURI[] = "exchange-message:/";

nsresult nsCreateExchangeBaseMessageURI(const nsACString& baseURI, nsCString &baseMessageURI)
{
  nsCAutoString tailURI(baseURI);
  // chop off exchange:/
  if (tailURI.Find(kExchangeRootURI) == 0)
    tailURI.Cut(0, PL_strlen(kExchangeRootURI));
  baseMessageURI = kExchangeMessageRootURI;
  baseMessageURI += tailURI;
  return NS_OK;
}

nsresult
nsExchangeMailFolder::CreateBaseMessageURI(const nsACString& aURI)
{
  return nsCreateExchangeBaseMessageURI(aURI, mBaseMessageURI);
}
